"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
@ 描述: 认证相关模型
"""
from datetime import datetime
from app.extensions import db


class Token(db.Model):
    """令牌模型"""
    __tablename__ = 'tokens'
    
    id = db.Column(db.Integer, primary_key=True)
    token = db.Column(db.String(255), unique=True, nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    expires_at = db.Column(db.DateTime, nullable=False)
    is_revoked = db.Column(db.Boolean, default=False, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    user = db.relationship('User', backref=db.backref('tokens', lazy='dynamic'))
    
    def __init__(self, user_id, expires_in=3600):
        import uuid
        from datetime import timedelta
        
        self.token = str(uuid.uuid4())
        self.user_id = user_id
        self.expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
    
    def is_expired(self):
        """检查令牌是否过期"""
        return datetime.utcnow() > self.expires_at
    
    def revoke(self):
        """撤销令牌"""
        self.is_revoked = True
        db.session.commit()
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'token': self.token,
            'user_id': self.user_id,
            'expires_at': self.expires_at.isoformat() if self.expires_at else None,
            'is_revoked': self.is_revoked,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def __repr__(self):
        return f'<Token {self.token[:10]}...>'


class RefreshToken(db.Model):
    """刷新令牌模型"""
    __tablename__ = 'refresh_tokens'
    
    id = db.Column(db.Integer, primary_key=True)
    token = db.Column(db.String(255), unique=True, nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    expires_at = db.Column(db.DateTime, nullable=False)
    is_revoked = db.Column(db.Boolean, default=False, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    user = db.relationship('User', backref=db.backref('refresh_tokens', lazy='dynamic'))
    
    def __init__(self, user_id, expires_in=2592000):  # 默认30天
        import uuid
        from datetime import timedelta
        
        self.token = str(uuid.uuid4())
        self.user_id = user_id
        self.expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
    
    def is_expired(self):
        """检查令牌是否过期"""
        return datetime.utcnow() > self.expires_at
    
    def revoke(self):
        """撤销令牌"""
        self.is_revoked = True
        db.session.commit()
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'token': self.token,
            'user_id': self.user_id,
            'expires_at': self.expires_at.isoformat() if self.expires_at else None,
            'is_revoked': self.is_revoked,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def __repr__(self):
        return f'<RefreshToken {self.token[:10]}...>'